<template>
  <a-modal
    :width="'80%'"
    :visible="visible"
    :title="t('autocode')"
    :cancelText="t('cancel')"
    :okText="t('submit')"
    @ok="submit"
    @cancel="cancel(false)"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :layout="'inline'"
      :rules="formRules"
    >
      <a-form-item
        ref="table_name"
        :label="t('table_name')"
        name="table_name"
        :style="{ width: '250px' }"
      >
       <a-input v-model:value="formState.table_name" />
      </a-form-item>

      <a-form-item
        ref="ename"
        :label="t('menu name')"
        name="ename"
        :style="{ width: '250px' }"
      >
        <a-input v-model:value="formState.ename" />
      </a-form-item>

      <a-form-item :label="t('menu')" :style="{ width: '300px' }">
        <a-tree-select
          v-model:value="formState.parent"
          style="width: 100%"
          :dropdown-style="{ maxHeight: '360px', overflow: 'auto' }"
          :tree-data="powers"
          :placeholder="t('higher power')"
          replace
          :fieldNames="{
            children: 'children',
            label: 'title',
            key: 'id',
            value: 'id',
          }"
        >
        </a-tree-select>
      </a-form-item>
    </a-form>

    <a-table
      :style="{ 'margin-top': '10px' }"
      :rowKey="'name'"
      :columns="columns" 
      :dataSource="datasource"
      :pagination="false"
    >
      <template #headerCell="{ column }">
        <span>
          {{ t(column.key) }}
        </span>
      </template>

      <!-- 列转换 -->
      <template #bodyCell="{ column, record }">
        <!-- 删除 -->
        <span v-if="column.delete">
          <a v-if="record[column.delete]"
            @click="deleteLine(record.key)"
          ><go2-icon :type="'InsertRowBelowOutlined'"></go2-icon></a>

          <a disabled v-else><go2-icon :type="'InsertRowBelowOutlined'"></go2-icon></a>

        </span>

        <span v-else-if="column.input">  
          <a-textarea rows="1" v-model:value="record[column.input]" :disabled="!record.operate"/>
        </span>

        <span v-else-if="column.number">  
          <a-input-number v-model:value="record[column.number]" :disabled="!record.operate"/>
        </span>

        <!-- 开关转换-->
        <span v-else-if="column.switch">
          <a-switch
          :disabled="!record.operate"
            v-model:checked="record[column.switch]" 
          />
        </span>
        <!-- 下拉   @change="changeSelect($event, column.select, record)"-->
        <span v-else-if="column.select1">
          <a-select
            ref="select"
            placeholder="选择数据类型"
            style="width: 120px"
            v-model:value="record.type"
            :disabled="!record.operate"
          >
            <a-select-option :value="'uint'">整型无符号</a-select-option>
            <a-select-option :value="'int64'">整型有符号</a-select-option> 
            <a-select-option :value="'float64'">浮点数</a-select-option>
            <a-select-option :value="'string'">文本</a-select-option>
            <a-select-option :value="'time'">日期时间</a-select-option> 
          </a-select>
        </span>

         <span v-else-if="column.select2">
          <a-select
            ref="select"
            placeholder="选择"
            style="width: 120px"
            v-model:value="record.inputtype"
            :disabled="!record.operate"
          >
            <a-select-option :value="'input'">单行输入</a-select-option>
            <a-select-option :value="'textarea'">文本域</a-select-option>
            <a-select-option :value="'switch'">开关</a-select-option>
            <a-select-option :value="'select'">下拉框</a-select-option>
            <a-select-option :value="'none'">无</a-select-option> 
          </a-select>
        </span>

        <!-- 原样输出 -->
        <span v-else-if="record">
          {{ record[column.dataIndex] }}
        </span>
      </template>
    </a-table>
    <a-button @click="addField" style="margin-top:10px" type="dashed" block>新增字段</a-button>
  </a-modal>
</template>
<script>
import { useI18n } from "vue-i18n";
import { message, Modal } from "ant-design-vue"; 
import { tableFields, create,permissionDir } from "@/core/api/module/autocode";
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
import {
  defineComponent,
  reactive,
  ref,
  toRaw,
  watch,
  onMounted,
  toRefs,
  createVNode,
} from "vue";
export default defineComponent({
  props: {
    visible: {
      type: Boolean,
    },
    record: {
      type: Object,
    },
  },
  emit: ["close"],
  setup(props, context) {
    const { t } = useI18n();
    const state = reactive({ 
      depts: [],
      showComponent: true,
      showPath: true,
      showCode: false,
       key:3,
      datasource: [{fieldname:"id",type:"uint",len:0,comment:"ID",notnull:true,list:false,search:false,inputtype:'none',operate:false,key:1},
      {fieldname:"created_at",type:"time",len:0,comment:"create_time",notnull:true,list:true,search:false,inputtype:'none',operate:false,key:2},
      {fieldname:"updated_at",type:"time",len:0,comment:"update_time",notnull:true,list:true,search:false,inputtype:'none',operate:false,key:3}],
      powers: [],
      loading: true,
    }); 
    const formRef = ref();

    const formState = reactive({
      parent: -1,
      ename: "",
      table_name: props.record.table_name,
    });

    const changeSwitch = (value, switchIndex, record) => {
      record[switchIndex] = value;
      return value;
    };

    const changeSelect = (value, SelectIndex, record) => {
      record[SelectIndex] = value;
      return value;
    };

    const deleteLine = (key) => {
        state.datasource = state.datasource.filter(item => item.key !== key);
    };

    const addField = ()=>{
        state.key++;
        state.datasource.unshift(
          {fieldname:"",type:"string",len:255,comment:"",notnull:false,list:true,search:true,inputtype:"textarea",operate:true,key:state.key}
        )
    }

    const columns = [
      { dataIndex: "fieldname", key: "fieldname" ,input:"fieldname"},
      { dataIndex: "type", key: "type" , select1: "type"},
      { dataIndex: "len", key: "len" , number: "len"},
      { dataIndex: "comment", key: "comment" ,input:"comment"},
      { dataIndex: "not null", key: "not null" , switch: "notnull"},
      { dataIndex: "open list", key: "open list", switch: "list" },
      { dataIndex: "open search", key: "open search", switch: "search" },
      { dataIndex: "open form", key: "open form", select2: "inputtype" }, 
      { dataIndex: "operate", key: "operate" ,delete:"operate" }, 
    ];

   

    const formRules = {
      ename: [{ required: true, message: "input first", trigger: "blur" }],
      table_name: [{ required: true, message: "input first", trigger: "blur" }],
    };

    watch(props, (props) => {});

    const submit = (e) => {
      formRef.value
        .validate()
        .then(() => {
          const postdata = Object.assign(
            {},
            { tabledata: toRaw(state.datasource) },
            formState
          );
          console.log(postdata); 
          create(postdata).then((response) => {
            if (response.code == 0) {
              message
                .success({ content: t("success"), duration: 1 })
                .then(() => {
                  cancel(true);
                });
            } else if (response.code == 2) {
              Modal.confirm({
                title: response.msg,
                icon: createVNode(ExclamationCircleOutlined),
                okText: t("ok"),
                cancelText: t("cancel"),
                onOk() {
                  message.loading({ content: t("loading") ,key:'confirm'});
                  postdata.relace = 1 ;
                  autocode(postdata).then((response) => {
                    if (response.code == 0) {
                      message
                        .success({ content: t("success"), duration: 1,key:'confirm' })
                        .then(() => {
                         // cancel(true);
                        });
                    } else {
                      message
                        .error({ content: "error", duration: 5,key:'confirm' })
                        .then(() => {
                          //cancel(false);
                        });
                    }
                  });
                },
              });
            } else {
              message.error({ content: response.msg, duration: 5 }).then(() => {
                //cancel(false);
              });
            }
          });
        })
        .catch((error) => {
          console.log("error", error);
        });
    };

    const cancel = (e = false) => {
      formRef.value.resetFields();
      context.emit("close", e);
    };

    const loadPower = () => {
      permissionDir().then((response) => {
        response.data = [
          {
            id: -1,
            title: t('no menus'),
            children: response.data,
          },
        ];
        state.powers = response.data;
      });
    };

    loadPower();

    return {
      t,
      ref,
      columns,
      fetch,
      ...toRefs(state),
      submit,
      cancel,
      formRef,
      formState,
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      changeSwitch,
      changeSelect,
      deleteLine,
      addField,
      formRules,
      fieldNames: {
        children: "children",
        title: "title",
        key: "id",
        value: "id",
      },
    };
  },
});
</script>